`timescale 1ns/1ps
// -----------------------------------------------------------------------------
// Copyright (c) 2014-2023 All rights reserved
// -----------------------------------------------------------------------------
// Project Name : 
// Author 		: HiDark
// File   		: mem2wb.sv
// Create 		: 2023-04-20 12:12:34
// Revise 		: 2023-04-20 12:12:34
// Abstract 	: 
// -----------------------------------------------------------------------------
`include "defines.svh"
module mem2wb(
	input	logic			clk,    // Clock
	input	logic			rst_n,  // Synchronous reset active low
	// write back register address and data
	input 	logic	[ 4:0]	wb_addr      ,
	input 	logic	[31:0]	alu_out ,
	input 	logic	[31:0]	mem_out ,
	// control signals
	input 	logic			wb_en,	 	//Register bank write enable
	input 	logic			wb_src, 	// 0 alu or 1 mem
	// write back register address
	output 	logic	[ 4:0]	wb_addr_mem2wb,
	output 	logic	[31:0]	wb_data_mem2wb ,
	// control signals
	output 	logic			wb_en_mem2wb 	//Register bank write enable
	);

//=================================================================================
// Signal declaration
//=================================================================================

	logic	[31:0]	alu_out_mem2wb ;
	logic			wb_src_mem2wb ;
//=================================================================================
// Body
//=================================================================================

	always_ff @(posedge clk) begin 
		if(~rst_n) 
			wb_en_mem2wb 	<=	'b0;	
		else 
			wb_en_mem2wb 	<=	wb_en;	
	end
	
	always_ff @(posedge clk) begin 
		if(~rst_n) 
			wb_addr_mem2wb	<=	'b0;			
		else
			wb_addr_mem2wb	<=	wb_addr;

	end
// read ram data need one cycle
	always_ff @(posedge clk) begin 
		if(~rst_n) begin
			alu_out_mem2wb	<=	'b0;	
			wb_src_mem2wb	<=	'b0;		
		end
		else begin
			alu_out_mem2wb	<=	alu_out;
			wb_src_mem2wb	<=	wb_src;			
		end
	end

	assign	wb_data_mem2wb	=	(wb_src_mem2wb == `SRC_ALU) ? alu_out_mem2wb : mem_out; 		


//=================================================================================
// Instantiation declaration
//=================================================================================




endmodule